/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.serializer;

import at.schauer.gregor.vienna.AbstractViennaIT;
import at.schauer.gregor.vienna.context.ViennaContextManager;
import at.schauer.gregor.vienna.exception.ViennaException;
import at.schauer.gregor.vienna.test.MathService;
import at.schauer.gregor.vienna.test.SimpleMathService;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Map;

import static org.junit.Assert.*;

/**
 * @author Gregor Schauer
 */
public class RMISerializerIT extends AbstractViennaIT {
	@Test
	public void test() throws Exception {
		try {
			RMISerializer<MathService> serializer = new RMISerializer<MathService>("127.0.0.1", Registry.REGISTRY_PORT);
			serializer.setViennaContext(ViennaContextManager.getInstance().getContext());
			MathService service = new SimpleMathService();

			Map<String, Object> map = serializer.save(service);
			assertEquals(SimpleMathService.class.getSimpleName(), map.get(RMISerializer.KEY));
			assertEquals(SimpleMathService.class, map.get("class"));
			assertEquals(service, map.get(RMISerializer.OBJECT));

			MathService remote = serializer.load(map);
			assertEquals(2.0, remote.calc("1 + 1"), 0.000001);
			assertNotSame(service, remote);

			try {
				serializer.delete(service);
				serializer.load(map);
				fail("delete (unbind) was not successful");
			} catch (ViennaException e) {
				// unbind successful
			}
		} catch (ViennaException e) {
			Logger.getLogger(RMISerializerIT.class).error(String.format("Test '%s' failed. Please verify that the 'hosts' file does not contain ambiguous entries.", this.getClass().getSimpleName()));
		} finally {
			try {
				for (String name : LocateRegistry.getRegistry().list()) {
					LocateRegistry.getRegistry().unbind(name);
				}
			} catch (Exception e) {
				// may happen
			}
		}
	}
}
